package crontab

import (
	"github.com/robfig/cron"
	"github.com/astaxie/beego"
	"log"
	"choujiang/models"
	"HTchoujiang/htmodels"
)

func StartCron() {
	spec := beego.AppConfig.String("cronTime") // 每天凌晨2：30
	c := cron.New()
	c.AddFunc(spec, tacleInvalidScores)
	c.Start()
	log.Print(spec)
	select {}
}

func tacleInvalidScores() {
	log.Println("\r\n*********Start clear invalid scores!*************\r\n")
	count, err := htmodels.HTUsersGetCount("", "id", 0)
	if err != nil {
		log.Println("get count error when clear invalid scores\r\n", err)
	}
	log.Println(count)
	currentUser := models.Users{}
	for i := 0; i < int(count); i++ {
		if models.UsersGetOneByOffset(&currentUser, i) != nil {
			log.Println("get user info error when clear invalid scores\r\ncurrent offset is:", i)
			continue
		}
		if currentUser.UserType != 0 {
			continue
		}

		point, err := htmodels.HTGetEfficientPoint(currentUser.Id, htmodels.HTgetUserLastCommitTime(currentUser.Id))
		if err != nil {
			log.Println("get user info error when clear invalid scores\r\ncurrent uid is:", currentUser.Id)
			continue
		}
		//log.Println(htmodels.HTgetUserLastCommitTime(currentUser.Id), point,currentUser.Id)
		if int64(point) == currentUser.UserCurrentPoint {
			continue
		}
		lastpoint := currentUser.UserCurrentPoint
		currentUser.UserCurrentPoint = int64(point)
		currentUser.UserLoseEffectPoint += int(lastpoint) - point
		if htmodels.HTUsersUpdate(&currentUser) != nil {
			log.Println("update user info error when clear invalid scores\r\ncurrent uid is:", currentUser.Id)
		}
	}
}
